package com.googlecode.cswish.security.type;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.cswish.security.Context;


/**
 * @author Jerry.Feng Date: Nov 8, 2007 2:04:16 PM
 * @version $id: $
 */
public class RuleSetAnd implements Calculation {

	protected boolean alwaysFalse;
	
	protected List<Calculation> expressList = new ArrayList<Calculation>();

	@Override
	public String execute(Context context) {
		return String.valueOf(executeBoolean(context));
	}

	@Override
	public boolean executeBoolean(Context context) {
		if (alwaysFalse) {
			return false;
		}
		
		for (Iterator<Calculation> iter = expressList.iterator(); iter.hasNext();) {
			Calculation expression = iter.next();
			
			boolean ret = true;
			ret &= expression.executeBoolean(context);
				
			if (ret) {
				return ret;
			}
		}
		return false;
	}
	
	public RuleSetAnd addRule(Calculation expression) {
		if (alwaysFalse) {
			// do nothing
		} else if (expression.executeBoolean(null)) {
			alwaysFalse = true;
		} else {
			expressList.add(expression);
		}
		return this;
	}

	@Override
	public String getCondition(boolean booleanCondition) {
		StringBuilder sb = new StringBuilder();
		for (Calculation express : expressList) {
			String condition = express.getCondition(booleanCondition);
			if (condition != null && condition.length() > 0) {
				if (sb.length() > 0) {
					sb.append(" && ");
				}
				sb.append('(').append(condition).append(')');
			}
		}
		return sb.toString();
	}
}